/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.sqlcipher.database;

import ohos.app.Context;
import ohos.global.resource.RawFileDescriptor;
import ohos.data.resultset.ResultSet;
import ohos.global.resource.RawFileEntry;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.rpc.MessageParcel;
import ohos.rpc.ReliableFileDescriptor;
import ohos.security.asset.AssetOperator;

import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * Some helper functions for using SQLite database to implement content providers.
 *
 * @hide
 */
public class SQLiteContentHelper {
    private static final HiLogLabel label = new HiLogLabel(HiLog.LOG_APP, 0x002A, "SQLiteContentHelper");
    private static ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);

    /**
     * Runs an SQLite query and returns an AssetFileDescriptor for the
     * blob in column 0 of the first row. If the first column does
     * not contain a blob, an unspecified exception is thrown.
     *
     * @param db Handle to a readable database.
     * @param sql SQL query, possibly with query arguments.
     * @param selectionArgs Query argument values, or {@code null} for no argument.
     * @return If no exception is thrown, a non-null AssetFileDescriptor is returned.
     * @throws FileNotFoundException If the query returns no results or the
     *         value of column 0 is NULL, or if there is an error creating the
     *         asset file descriptor.
     */
/*    public static RawFileDescriptor getBlobColumnAsAssetFile(Context context, SQLiteDatabase db, String sql,
                                                             String[] selectionArgs) throws FileNotFoundException {
        FileDescriptor fd = null;

        try {
            final MessageParcel file = simpleQueryForBlobMemoryFile(db, sql, selectionArgs);
            if (file == null) {
                throw new FileNotFoundException("No results.");
            }
            fd = file.readFileDescriptor();
            RawFileEntry assetManager = context.getResourceManager().getRawFileEntry(file);
            RawFileDescriptor afd = assetManager.openRawFileDescriptor();
            return afd;
        } catch (IOException ex) {
            throw new FileNotFoundException(ex.toString());
        }
    }*/

    /**
     * Runs an SQLite query and returns a MemoryFile for the
     * blob in column 0 of the first row. If the first column does
     * not contain a blob, an unspecified exception is thrown.
     *
     * @param db database
     * @param sql string
     * @param selectionArgs arguments
     * @return A memory file, or {@code null} if the query returns no results
     *         or the value column 0 is NULL.
     * @throws IOException If there is an error creating the memory file.
     */
    // TODO: make this native and use the SQLite blob API to reduce copying
    private static MessageParcel simpleQueryForBlobMemoryFile(SQLiteDatabase db, String sql,
                                                           String[] selectionArgs) throws IOException {
        ResultSet cursor = db.rawQuery(sql, selectionArgs);
        if (cursor == null) {
            return null;
        }
        try {
            if (!cursor.goToFirstRow()) {
                return null;
            }
            byte[] bytes = cursor.getBlob(0);
            if (bytes == null) {
                return null;
            }
            buffer.put(bytes, 0, bytes.length);
            buffer.flip();
            MessageParcel file = MessageParcel.obtain();
            file.writeRawData(bytes, bytes.length);

            //   file.deactivate();
            return file;
        } finally {
            cursor.close();
        }
    }

}

